<template>
    <div>
        <input type="file" ref="input" v-show="false" @change="onChange">
        <el-dialog :visible.sync="isShowCurImage" title="图片剪裁" width="400px">
            <MmvCutImage :img="preview" v-if="isShowCurImage" @cancel="isShowCurImage=false" @submit="upload"></MmvCutImage>
        </el-dialog>
        <div @click="onClick" style="display:inline-block">
            <slot></slot>
        </div>
        <slot name="tip"></slot>
        <!-- 预览图片 -->
        <div class="preview-wrap" v-if="preview">
            <el-image class="preview" :src="preview" fit="contain"></el-image>
            <el-button type="danger" icon="el-icon-delete-solid" @click="onClear"></el-button>
        </div>
    </div>
</template>

<script>
import MmvCutImage from './mmv-cut-Image.vue';

export default {
    name: 'mmv-upload-image',
    components: {
        MmvCutImage,
    },
    data() {
        return {
            isShowCurImage: false,
            preview: '',
        };
    },
    destroyed() {
        window.URL.revokeObjectURL(this.preview);
    },
    methods: {
        onClick() {
            this.$refs.input.click();
        },

        previewFun(image) {
            window.URL.revokeObjectURL(this.preview);
            this.preview = window.URL.createObjectURL(image);
        },

        onChange(evt) {
            const file = evt.target.files[0];
            evt.target.value = null;
            this.previewFun(file);
            this.isShowCurImage = true;
        },

        upload(blob) {
            this.previewFun(blob);
            this.isShowCurImage = false;
            const url = this.preview;
            this.$emit('upImg', url); // 这里指上传成功后拿到的url
        },

        onClear() {
            this.preview = '';
            window.URL.revokeObjectURL(this.preview);
            this.$emit('input', '');
        },

    },
}
</script>

<style lang="scss" scoped>
.preview-wrap {
    display: flex;
    align-items: flex-start;
}
.preview {
    width: 583px;
    height: 254px;
    border: 1px solid #ddd;
    margin-right: 10px;
}
</style>
